<template>
  <div>
    <BasicCard>
      <BasicVxeForm ref="formRef" :formOptions="formOptions" @search="handleSearch" />
    </BasicCard>

    <el-scrollbar>
      <div class="card-box">
        <NumberCard
          :cardOptions="
            numberCardOptions[gongXuName]
              ? numberCardOptions[gongXuName]
              : numberCardOptions['default']
          "
          :data="groupData"
        />
      </div>
    </el-scrollbar>

    <BasicCard>
      <BasicVxeTable v-bind="classifyGridOptions" />
    </BasicCard>

    <BasicCard>
      <BasicVxeTable v-bind="detailGridOptions" />
    </BasicCard>
  </div>
</template>

<script setup lang="ts">
  import dayjs from 'dayjs'
  import NumberCard from './components/NumberCard.vue'
  import {
    getCurrentAndLastBanCi,
    getGongXuJiTaiOptions,
    formatNumber,
    formatNumbersInObject,
    splitTsIdToTime,
    getQuYuOptions,
    getWuLiaoOptions
  } from '@/utils'
  import { numberCardOptions, columns } from './data'
  import {
    postJiTaiBaoBiao_gongXu,
    postWuLiaoBaoBiao_gongXu,
    type PostJiTaiBaoBiao_gongXuResult,
    type PostWuLiaoBaoBiao_gongXuResult
  } from '@/api/shuJuBaoBiao'

  const props = defineProps<{
    gongXuName: string
    gongXuId: string
    isQuYu: boolean
  }>()

  interface FormV0 {
    quYuValue: string
    pageType: 'material' | 'equipment'
    equipment: string[]
    material: string[]
    tsIdSelect: ShiftSchedulePickerData
  }

  const { t } = useI18n()

  const groupData = ref<
    PostJiTaiBaoBiao_gongXuResult['groupdata'] | PostWuLiaoBaoBiao_gongXuResult['groupdata']
  >({} as any)

  // 班次
  const shiftOptions = ref<LabelValueOption[]>([])
  // 区域
  const quYuOptions = ref<LabelValueOption[]>([])
  // 品种
  const materialOptions = ref<LabelValueOption[]>([])
  // 机台
  const equipmentOptions = ref<LabelValueOption[]>([])

  const showTablesLoading = () => {
    classifyGridOptions.loading = true
    detailGridOptions.loading = true
  }

  const hideTablesLoading = () => {
    classifyGridOptions.loading = false
    detailGridOptions.loading = false
  }

  const handlePageTypeChange = (type: 'material' | 'equipment') => {
    // 展示对应选项
    const materialItem = formRef.value?.$form?.getItemByField('material')
    const equipmentItem = formRef.value?.$form?.getItemByField('equipment')
    if (materialItem && equipmentItem) {
      if (type === 'equipment') {
        materialItem.visible = false
        equipmentItem.visible = true
      } else {
        materialItem.visible = true
        equipmentItem.visible = false
      }

      // 触发时间更新
      getTsIdSelect()
    } else {
      console.error('未找到对应item')
    }

    if (type) {
      // 切换对应的table
      classifyGridOptions.columns = columns[props.gongXuName][type].classifyColumns
      detailGridOptions.columns = columns[props.gongXuName][type].detailColumns
    }
  }

  // 获取tsIdSelect选择器的数据和选项
  const getTsIdSelect = async () => {
    const banCiOpt = await getCurrentAndLastBanCi(
      props.isQuYu ? formOptions.data!.quYuValue : props.gongXuId,
      { isQy: props.isQuYu, isGetLast: true }
    )

    formOptions.data!.tsIdSelect = banCiOpt.banCiInfo
    shiftOptions.value = banCiOpt.shiftOptions

    // 查询对应物料
    handleTsIdChange()
  }

  const handleTsIdChange = async () => {
    showTablesLoading()

    // 获取物料
    const { pageType, tsIdSelect, quYuValue } = formOptions.data!
    if (pageType === 'material') {
      materialOptions.value = await getWuLiaoOptions(
        {
          areaId: quYuValue,
          craftNodeName: props.gongXuName,
          tsidStart: tsIdSelect.startTsId,
          tsidEnd: tsIdSelect.endTsId
        },
        { isQy: props.isQuYu }
      )
      // 全选
      formOptions.data!.material = materialOptions.value.map((v) => v.value)
      handleSearch()
    } else if (pageType === 'equipment') {
      equipmentOptions.value = await getGongXuJiTaiOptions(
        {
          areaId: quYuValue,
          craftNodeId: props.gongXuId
        },
        { isQy: props.isQuYu }
      )
      // 全选
      formOptions.data!.equipment = equipmentOptions.value.map((v) => v.value)
      handleSearch()
    }
  }

  const handleSearch = async () => {
    try {
      const { pageType } = formOptions.data!
      showTablesLoading()
      if (pageType === 'material') {
        await getDataByMaterial()
      } else if (pageType === 'equipment') {
        await getDataByEquipment()
      }
    } catch (e) {
      console.error(e)
    } finally {
      hideTablesLoading()
    }
  }

  // 根据班次、物料，查询班报
  const getDataByMaterial = async () => {
    console.log('根据班次、物料，查询班报')
    const { tsIdSelect, material } = formOptions.data!

    let data = {
      tsIdStart: tsIdSelect.startTsId,
      tsIdEnd: tsIdSelect.endTsId,
      craftNodeName: props.gongXuName,
      materialIds: material
    }
    await postWuLiaoBaoBiao_gongXu(props.gongXuName, data).then((res) => {
      classifyGridOptions.data = res.classifydata.map((v) => formatNumbersInObject(v))

      detailGridOptions.data = res.detaildata
        .map((v) => {
          const item: Recordable = formatNumbersInObject(v)
          item.nameAngZuHao = item.machineName + '#' + item.groupNo
          item.begin = dayjs(item.begin).format('YYYY-MM-DD HH:mm')
          item.end = dayjs(item.end).format('YYYY-MM-DD HH:mm')
          item.tsid = splitTsIdToTime(item.tsid) as any
          return item
        })
        .sort((a, b) => a.machineName - b.machineName)

      for (let key in res.groupdata) {
        if (key == 'actualYarnWeight') {
          res.groupdata.actualYarnWeight = formatNumber(res.groupdata.actualYarnWeight, 0)
        } else if (key == 'theoreticalYarnWeight') {
          res.groupdata.theoreticalYarnWeight = formatNumber(res.groupdata.theoreticalYarnWeight, 0)
        } else if (key == 'speedAvg1') {
          res.groupdata.speedAvg1 = formatNumber(res.groupdata.speedAvg1, 0)
        } else if (key == 'AveageOutPut') {
          res.groupdata.AveageOutPut = formatNumber(res.groupdata.AveageOutPut, 0)
        } else if (key == 'powerPerWeight') {
          res.groupdata.powerPerWeight = formatNumber(res.groupdata.powerPerWeight, 0)
        } else if (key == 'breakWeight') {
          res.groupdata.breakWeight = formatNumber(res.groupdata.breakWeight, 0)
        } else if (key == 'efcRun') {
          res.groupdata.efcRun = formatNumber(res.groupdata.efcRun)
        } else if (key == 'power') {
          res.groupdata.power = formatNumber(res.groupdata.power)
        } else if (key == 'actualPowerPerWeight') {
          res.groupdata.actualPowerPerWeight = formatNumber(res.groupdata.actualPowerPerWeight)
        }
      }

      if (props.gongXuName == '织机') {
        res.groupdata.efcRun = formatNumber(res.groupdata.efcRun)
        res.groupdata.s11003 = formatNumber(res.groupdata.s11003)
        res.groupdata.s11004 = formatNumber(res.groupdata.s11004, 0)
        res.groupdata.stopTimes = formatNumber(res.groupdata.stopTimes)
      }

      groupData.value = res.groupdata
      console.log(groupData.value)

      classifyGridOptions.columns!.forEach((column) => {
        if (['实际吨纱耗电(kwh/T)', '理论吨纱耗电(kwh/T)'].includes(column.title!)) {
          column.visible = res.groupdata.isHasEnergy
        }
      })
      detailGridOptions.columns!.forEach((column) => {
        if (['实际吨纱耗电(kwh/T)', '理论吨纱耗电(kwh/T)'].includes(column.title!)) {
          column.visible = res.groupdata.isHasEnergy
        }
      })
    })
  }

  // 根据班次、机台，查询班报
  const getDataByEquipment = async () => {
    console.log('根据班次、机台，查询班报')

    const { tsIdSelect, equipment } = formOptions.data!
    let data = {
      tsIdStart: tsIdSelect.startTsId,
      tsIdEnd: tsIdSelect.endTsId,
      craftNodeName: props.gongXuName,
      machineDocumentIds: equipment
    }
    await postJiTaiBaoBiao_gongXu(props.gongXuName, data).then((res) => {
      classifyGridOptions.data = res.classifydatas.map((v) => formatNumbersInObject(v))

      detailGridOptions.data = res.detaildatas
        .map((v) => {
          const item: Recordable = formatNumbersInObject(v)
          item.nameAngZuHao = item.machineName + '#' + item.groupNo
          item.begin = dayjs(item.begin).format('YYYY-MM-DD HH:mm')
          item.end = dayjs(item.end).format('YYYY-MM-DD HH:mm')
          item.tsid = splitTsIdToTime(item.tsid) as any
          return item
        })
        .sort((a, b) => a.machineName - b.machineName)

      for (let key in res.groupdata) {
        if (key == 'actualYarnWeight') {
          res.groupdata.actualYarnWeight = formatNumber(res.groupdata.actualYarnWeight, 0)
        } else if (key == 'theoreticalYarnWeight') {
          res.groupdata.theoreticalYarnWeight = formatNumber(res.groupdata.theoreticalYarnWeight, 0)
        } else if (key == 'speedAvg1') {
          res.groupdata.speedAvg1 = formatNumber(res.groupdata.speedAvg1, 0)
        } else if (key == 'aveageOutPut') {
          res.groupdata.AveageOutPut = formatNumber(res.groupdata.AveageOutPut, 0)
        } else if (key == 'powerPerWeight') {
          res.groupdata.powerPerWeight = formatNumber(res.groupdata.powerPerWeight, 0)
        } else if (key == 'breakWeight') {
          res.groupdata.breakWeight = formatNumber(res.groupdata.breakWeight, 0)
        } else if (key == 'efcRun') {
          res.groupdata.efcRun = formatNumber(res.groupdata.efcRun)
        } else if (key == 'power') {
          res.groupdata.power = formatNumber(res.groupdata.power)
        } else if (key == 'actualPowerPerWeight') {
          res.groupdata.actualPowerPerWeight = formatNumber(res.groupdata.actualPowerPerWeight)
        }
      }

      classifyGridOptions.columns!.forEach((column) => {
        if (['吨纱耗电(kwh/T)', '耗电(kwh)'].includes(column.title!)) {
          column.visible = res.groupdata.isHasEnergy
        }
      })
      detailGridOptions.columns!.forEach((column) => {
        if (['吨纱耗电(kwh/T)', '耗电(kwh)'].includes(column.title!)) {
          column.visible = res.groupdata.isHasEnergy
        }
      })

      groupData.value = res.groupdata
    })
  }

  const formRef = ref<BasicFormInstance>()
  const formOptions = reactive<BasicFormProps<FormV0>>({
    titleWidth: 55,
    data: {
      pageType: 'material'
    } as FormV0,
    items: [
      {
        field: 'pageType',
        className: 'is-full',
        itemRender: {
          name: 'ElRadioGroup',
          options: [
            { label: t('custom.品种'), value: 'material' },
            { label: t('custom.机台'), value: 'equipment' }
          ],
          events: {
            change: (_params, e) => {
              handlePageTypeChange(e)
            }
          }
        }
      },
      {
        field: 'quYuValue',
        visibleMethod: () => props.isQuYu,
        itemRender: {
          name: 'ElSelect',
          options: computed(() => quYuOptions.value) as unknown as LabelValueOption[],
          props: { style: 'width: 100px' },
          events: {
            change: () => {
              getTsIdSelect()
            }
          }
        }
      },
      {
        field: 'tsIdSelect',
        title: t('system.时间'),
        itemRender: {
          name: 'ShiftSchedulePicker',
          props: {
            shiftOptions: computed(() => shiftOptions.value) as unknown as LabelValueOption[]
          },
          events: {
            confirm: handleTsIdChange
          }
        }
      },
      {
        field: 'material',
        title: t('custom.物料'),
        itemRender: {
          name: 'SelectModal',
          props: {
            modalConfig: {
              title: t('system.列表选择', { name: t('custom.物料') }),
              options: computed(() => materialOptions.value)
            }
          }
        }
      },
      {
        field: 'equipment',
        title: t('custom.机台'),
        visible: false,
        itemRender: {
          name: 'SelectModal',
          props: {
            modalConfig: {
              title: t('system.列表选择', { name: t('custom.机台') }),
              options: computed(() => equipmentOptions.value)
            }
          }
        }
      },
      {
        field: 'form-actions',
        itemRender: {
          name: 'ActionButtons',
          children: [{ name: 'search' }]
        }
      }
    ]
  })

  const classifyGridExportName = computed(() => {
    const formData = formRef.value?.getFormData() as FormV0
    const tsIdSelect = formData.tsIdSelect || {}
    return `${t(`custom.${props.gongXuName}`)}${t(`export.基础报表`)}_${t(`export.分类报表`)}(${tsIdSelect.startTime} ${tsIdSelect.startShiftName}~${tsIdSelect.endTime} ${tsIdSelect.endShiftName})`
  })

  const detailGridExportName = computed(() => {
    const formData = formRef.value?.getFormData() as FormV0
    const tsIdSelect = formData.tsIdSelect || {}
    return `${t(`custom.${props.gongXuName}`)}${t(`export.基础报表`)}_${t(`export.详细报表`)}(${tsIdSelect.startTime} ${tsIdSelect.startShiftName}~${tsIdSelect.endTime} ${tsIdSelect.endShiftName})`
  })

  const classifyGridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: t('custom.分类报表'),
      isCustom: true,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `shuJuBaoBiao-jiChuBaoBiao-${props.gongXuName}-classify`, // id用于缓存,务必配置
    maxHeight: 480,
    columns: columns[props.gongXuName]['material']['classifyColumns'],
    toolbarConfig: {}, // 工具栏
    exportConfig: {
      filename: classifyGridExportName as unknown as string
    }
  })

  const detailGridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: t('custom.详细报表'),
      isCustom: true,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `shuJuBaoBiao-jiChuBaoBiao-${props.gongXuName}-detail`, // id用于缓存,务必配置
    maxHeight: 480,
    columns: columns[props.gongXuName]['material']['detailColumns'],
    toolbarConfig: {}, // 工具栏
    exportConfig: {
      filename: detailGridExportName as unknown as string
    }
  })

  onMounted(async () => {
    // 有区域先拿区域 再用区域选项第一个去拿班次
    if (props.isQuYu) {
      quYuOptions.value = await getQuYuOptions()
      formOptions.data!.quYuValue = quYuOptions.value[0].value
    }
    handlePageTypeChange('material')
  })
</script>

<style>
  .is-full {
    flex: 1;
  }

  .card-box {
    display: flex;

    /* margin-bottom: 20px; */
  }
</style>
